<template>
  <el-main class="dashboard-container">
    <!-- 统计卡片区 -->
    <el-row :gutter="20" class="stats-row">
      <el-col 
        v-for="(stat, index) in statsData" 
        :key="index"
        :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <dashboard-stat-card :stat="stat" />
      </el-col>
    </el-row>

    <!-- 核心图表区 -->
    <el-row :gutter="20" class="chart-area">
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <i class="el-icon-pie-chart neon-icon"></i>
              <span>图书分类统计</span>
            </div>
          </template>
          <div v-loading="chartLoading" id="main1" class="echart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <i class="el-icon-trophy neon-icon"></i>
              <span>热门图书排行榜</span>
            </div>
          </template>
          <div v-loading="chartLoading" id="main2" class="echart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 公告区 -->
    <el-card class="announcement-card">
      <template #header>
        <div class="card-header">
          <i class="el-icon-megaphone neon-icon"></i>
          <span>最新公告</span>
        </div>
      </template>
      <el-timeline v-if="noticeList.length > 0">
        <el-timeline-item
          v-for="(notice, index) in noticeList"
          :key="index"
          :timestamp="notice.createTime"
          placement="top"
          class="timeline-item"
        >
          <div class="notice-content">
            <h4 class="notice-title">{{ notice.noticeTitle }}</h4>
            <p class="notice-text">{{ notice.noticeContent }}</p>
          </div>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="暂无公告" :image-size="80"></el-empty>
    </el-card>
  </el-main>
</template>

<script>
import { getUserType, getUserId } from '@/utils/auth'
import { getReaderCountApi, getApplyReaderCountApi } from '@/api/reader'
import { getBorrowApplyCountApi, getBorrowReturnCountApi } from '@/api/borrow'
import { categoryCountApi } from '@/api/category'
import { getHotBookApi } from '@/api/book'
import { getTopListApi } from '@/api/notice'
import DashboardStatCard from '@/components/DashboardStatCard.vue'

export default {
  name: 'Dashboard',
  components: { DashboardStatCard },
  data() {
    return {
      statsData: [
        { 
          icon: 'el-icon-user-solid',
          value: 0,
          label: '读者总数',
          gradient: 'linear-gradient(135deg, #6ab7ff 0%, #36d1dc 100%)'
        },
        {
          icon: 'el-icon-document-checked',
          value: 0,
          label: '读者待审核',
          gradient: 'linear-gradient(135deg, #6ab7ff 0%, #00f7ff 100%)'
        },
        {
          icon: 'el-icon-notebook-2',
          value: 0,
          label: '借书待审核',
          gradient: 'linear-gradient(135deg, #00f7ff 0%, #36d1dc 100%)'
        },
        {
          icon: 'el-icon-alarm-clock',
          value: 0,
          label: '到期待还书',
          gradient: 'linear-gradient(135deg, #36d1dc 0%, #6ab7ff 100%)'
        }
      ],
      noticeList: [],
      chartLoading: true,
      roleType: '',
      tableData: [],
      roleId: ''
    }
  },
  mounted() {
    this.initCharts()
    this.loadData()
    
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    // 组件销毁前移除监听器
    window.removeEventListener('resize', this.resizeCharts)
  },
  methods: {
    // 调整图表大小
    resizeCharts() {
      const chart1 = this.$echarts.getInstanceByDom(document.getElementById('main1'))
      const chart2 = this.$echarts.getInstanceByDom(document.getElementById('main2'))
      
      if (chart1) {
        chart1.resize()
      }
      
      if (chart2) {
        chart2.resize()
      }
    },

    async loadData() {
      try {
        const [readerCount, applyReader, borrowApply, borrowReturn, notices] = await Promise.all([
          this.getReaderCount(),
          this.getApplyReaderCount(),
          this.getBorrowApplyCount(),
          this.getBorrowReturnCount(),
          this.getNoticeList()
        ])
        
        this.statsData[0].value = readerCount
        this.statsData[1].value = applyReader
        this.statsData[2].value = borrowApply
        this.statsData[3].value = borrowReturn
        this.noticeList = notices
      } catch (error) {
        console.error('数据加载失败:', error)
        this.$message.error('数据加载失败，请稍后重试')
      } finally {
        this.chartLoading = false
      }
    },

    initCharts() {
      this.$echarts.registerTheme('tech', {
        color: ['#6ab7ff', '#00f7ff', '#72d6ff'],
        backgroundColor: '#ffffff',
        textStyle: { color: '#2c3e50' },
        title: { textStyle: { fontSize: 18, color: '#2c3e50' } }
      })

      this.myechert1()
      this.myechert2()
    },

    // 原有数据获取方法
    async getNoticeList() {
      try {
        const res = await getTopListApi()
        if (res?.code === 200) return res.data
        return []
      } catch (error) {
        console.error('公告加载失败:', error)
        return []
      }
    },

    async getBorrowReturnCount() {
      const res = await getBorrowReturnCountApi({
        userType: getUserType(),
        userId: getUserId()
      })
      return res?.code === 200 ? res.data : 0
    },

    async getBorrowApplyCount() {
      const res = await getBorrowApplyCountApi({
        userType: getUserType(),
        userId: getUserId()
      })
      return res?.code === 200 ? res.data : 0
    },

    async getReaderCount() {
      const res = await getReaderCountApi()
      return res?.code === 200 ? res.data : 0
    },

    async getApplyReaderCount() {
      const res = await getApplyReaderCountApi()
      return res?.code === 200 ? res.data : 0
    },

    // 图表初始化方法
    async myechert1() {
      const myChart = this.$echarts.init(document.getElementById('main1'), 'tech')
      const res = await categoryCountApi()
      
      const option = {
        backgroundColor: '#ffffff',
        tooltip: { 
          trigger: 'axis',
          formatter: '{b}: {c}本'
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: { 
              show: true, 
              title: '保存图片',
              backgroundColor: '#ffffff',
              pixelRatio: 2
            }
          },
          right: 20,
          top: 0
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '40px',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: res?.data?.names || [],
          axisLabel: {
            rotate: 45,
            formatter: (value) => {
              return value.length > 4 ? value.slice(0,4)+'...' : value
            }
          }
        },
        yAxis: { type: 'value' },
        series: [{
          type: 'bar',
          data: res?.data?.counts || [],
          itemStyle: {
            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#6ab7ff' },
              { offset: 1, color: '#00f7ff' }
            ])
          }
        }]
      }
      myChart.setOption(option)
    },

    async myechert2() {
      const myChart = this.$echarts.init(document.getElementById('main2'), 'tech')
      const res = await getHotBookApi()
      
      const option = {
        backgroundColor: '#ffffff',
        tooltip: { 
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}次 ({d}%)'
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: { 
              show: true, 
              title: '保存图片',
              backgroundColor: '#ffffff',
              pixelRatio: 2
            }
          },
          right: 20,
          top: 0
        },
        legend: { 
          orient: 'vertical', 
          left: '5%',
          bottom: '5%',
          type: 'scroll',
          textStyle: {
            fontSize: 12
          },
          formatter: function(name) {
            // 截断长文本
            return name.length > 12 ? name.slice(0, 12) + '...' : name;
          }
        },
        series: [{
          name: '借阅次数',
          type: 'pie',
          radius: ['30%', '60%'],
          center: ['65%', '45%'],  // 将饼图移到右侧
          data: res?.data || [],
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            show: false  // 隐藏饼图上的文字标签
          },
          labelLine: {
            show: false  // 隐藏连接线
          }
        }]
      }
      myChart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
$primary: #6ab7ff;
$neon: #00f7ff;
$bg: #f5f9ff;
$dark: #2c3e50;

.dashboard-container {
  background: $bg;
  padding: 20px;
  min-height: calc(100vh - 60px);
}

.stats-row {
  margin-bottom: 20px;
  
  .el-col {
    transition: transform 0.3s;
    padding: 10px !important;
    
    &:hover {
      transform: translateY(-5px);
    }
  }
}

.chart-card {
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba($primary, 0.1);
  border: none;
  background-color: #ffffff;
  
  .echart-container {
    height: 350px;
    width: 100%;
    background-color: #ffffff;
  }
  
  ::v-deep .el-card__body {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    align-items: center;
    font-size: 16px;
    
    .neon-icon {
      color: $neon;
      margin-right: 10px;
      font-size: 20px;
      text-shadow: 0 0 8px rgba($neon, 0.3);
    }
    
    span {
      font-weight: 600;
      color: $dark;
    }
  }
}

.announcement-card {
  margin-top: 20px;
  border: 1px solid rgba($primary, 0.2);
  border-radius: 12px;
  
  .card-header {
    display: flex;
    align-items: center;
    font-size: 16px;
    
    .neon-icon {
      color: $neon;
      margin-right: 10px;
      font-size: 20px;
      text-shadow: 0 0 8px rgba($neon, 0.3);
    }
    
    span {
      font-weight: 600;
      color: $dark;
    }
  }
  
  .timeline-item {
    padding: 10px 0;
    
    .notice-title {
      margin: 0;
      color: $dark;
      font-size: 14px;
    }
    
    .notice-text {
      margin: 5px 0 0;
      color: lighten($dark, 20%);
      font-size: 13px;
      line-height: 1.5;
    }
  }
}

@media (max-width: 768px) {
  .chart-card {
    .echart-container {
      height: 250px;
    }
  }
  
  .stats-row .el-col {
    margin-bottom: 15px;
  }
}
</style>